﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NewUI.Component;
using NewUI.Service.Common;
using NewUI.Service.Hsl;

namespace NewUI.ViewModels;

public partial class MembraneRollViewModel : ViewModelBase
{
    //10.10.10.100
    //
    static string ip1 = "10.168.1.2";
    static string ip2 = "10.10.10.100";
    private PlcJuanCaiService PlcJuanCaiService { get; set; } = new(ip2);
    private PlcJuanCaiServiceHsl PlcJuanCaiServiceHsl { get; set; } = new(ip1);

    [ObservableProperty] private string _lastSavedFilePath; // 存储最后保存的文件路径
    [ObservableProperty] private string _buttonText = "读取数据";
    [ObservableProperty] private bool _isButtonEnabled;
    [ObservableProperty] private string _packingJuanCaiData = "数据为空";
    [ObservableProperty] private string _jCCMData = "数据为空";
    [ObservableProperty] private string _jCMiddleData = "数据为空";
    [ObservableProperty] private string _jCSSDRRPInData = "数据为空";
    [ObservableProperty] private string _weightWriteBackData = "数据为空";
    [ObservableProperty] private bool _isPolling; // 轮询状态
    private DispatcherTimer _pollingTimer;
    
    StringBuilder PackingJuanCaibuilder = new();
    StringBuilder JCCMDatabuilder = new();
    StringBuilder JCMiddleDatabuilder = new();
    StringBuilder JCSSDRRPInDatabuilder = new();
    StringBuilder WeightWriteBackDatabuilder = new();

    public MembraneRollViewModel()
    {
        // 获取exe所在目录
        string exeDirectory = AppContext.BaseDirectory;
        // 创建子目录
        string subDirectory = Path.Combine(exeDirectory, "ReadData");
        LastSavedFilePath = subDirectory;
        // 初始化定时器，设置500ms间隔
        _pollingTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(500)
        };
        _pollingTimer.Tick += async (s, e) => await PollingTick();
    }

    private void StartPolling()
    {
        _isPolling = true;
        _pollingTimer.Start();
        PackingJuanCaibuilder.Append("读取[PackingJuanCai]数据开始：----------------------------------");
        PackingJuanCaibuilder.Append(Environment.NewLine);
        JCCMDatabuilder.Append("读取[JCCMData]数据开始：----------------------------------");
        JCCMDatabuilder.Append(Environment.NewLine);
        JCMiddleDatabuilder.Append("读取[JCMiddleData]数据开始：----------------------------------");
        JCMiddleDatabuilder.Append(Environment.NewLine);
        JCSSDRRPInDatabuilder.Append("读取[JCSSDRRPInData]数据开始：----------------------------------");
        JCSSDRRPInDatabuilder.Append(Environment.NewLine);
        WeightWriteBackDatabuilder.Append("读取[WeightWriteBackData]数据开始：----------------------------------");
        WeightWriteBackDatabuilder.Append(Environment.NewLine);
    }

    private void StopPolling()
    {
        _isPolling = false;
        _pollingTimer.Stop();
        ToastManager.ShowSuccessToast("读取数据已停止!");
    }

    private async Task PollingTick()
    {
        await DoTask();
    }

    public async Task DoTask()
    {
        try
        {
            await doReadDataAsync(0,"PackingJuanCai");
            await doReadDataAsync(636,"JC_CM");
            await doReadDataAsync(1272,"JC_Middle");
            await doReadDataAsync(1910,"JC_SSD_RRP_In");
            await doReadDataAsync(2546,"Weight_WriteBack");
        }
        catch (Exception e) 
        {
            ToastManager.ShowErrorToast(e.Message);
        }
    }
    
    [RelayCommand]
    public async Task WritePackingJuanCaiDataAsync()
    {
        var data = new PlcJuanCai()
        {
          
            BianHao = "JC20230730001",
            HouDu = 15,
            
            Treatment = "表面处理",
            
            Id = 1001,
            ZhiJing = 400,
            // ChangDu = 600,
            From_SSD_No = 2,
            KuanDu = 600,
            DJ_class = 1,
            Need_QPM = true,
            Need_ZG = true,
            Need_PMD = true,
            
            ZhongLiang = "",
            // 设置其他字段...
            KH_OK = true,
            Print_Top_OK = true,
            DZ_Tetect_OK = true
        };

        bool success = PlcJuanCaiServiceHsl.WriteJuanCaiData(data,1910);
    
        if (success)
            ToastManager.ShowSuccessToast("数据写入成功!");
        else
            ToastManager.ShowErrorToast("数据写入失败!");
    }

    [RelayCommand]
    public async Task DoTaskSingle()
    {
        await DoTask();
    }
    
    [RelayCommand]
    public async Task ReadPackingJuanCaiDataAsync()
    {
        //按钮未执行
        if (!IsButtonEnabled)
        {
            StartPolling();
            ButtonText = "停止读取";
            IsButtonEnabled = true;
            ToastManager.ShowSuccessToast("正在读取数据!");
        }
        else
        {
            StopPolling();
            ButtonText = "读取数据";
            IsButtonEnabled = false;
            ToastManager.ShowSuccessToast("停止读取数据!");
        }
       
    }
    
    [RelayCommand]
    public void OpenSaveDirectory()
    {
        try
        {
            if (!string.IsNullOrEmpty(LastSavedFilePath) && Directory.Exists(LastSavedFilePath))
            {
                OpenDirectoryInExplorer(LastSavedFilePath);
                return;
            }
            // 如果有最后保存的文件路径，打开其所在目录
            if (!string.IsNullOrEmpty(LastSavedFilePath) && File.Exists(LastSavedFilePath))
            {
                string directory = Path.GetDirectoryName(LastSavedFilePath);
                OpenDirectoryInExplorer(directory);
                return;
            }
            
            // 否则打开exe所在目录
            string exeDirectory = AppContext.BaseDirectory;
            OpenDirectoryInExplorer(exeDirectory);
        }
        catch (Exception ex)
        {
            PackingJuanCaiData += $"\n\n打开目录时出错: {ex.Message}";
        }
    }

    private void OpenDirectoryInExplorer(string path)
    {
        if (Directory.Exists(path))
        {
            // 使用Process打开资源管理器
            Process.Start(new ProcessStartInfo
            {
                FileName = "explorer.exe",
                Arguments = path,
                UseShellExecute = true
            });
        }
    }

    [RelayCommand]
    public async Task RestData()
    {
        PackingJuanCaiData = "";
        PackingJuanCaibuilder.Clear();
        JCCMData = "";
        JCCMDatabuilder.Clear();
        JCMiddleData = "";
        JCMiddleDatabuilder.Clear();
        JCSSDRRPInData = "";
        JCSSDRRPInDatabuilder.Clear();
        WeightWriteBackData = "";
        WeightWriteBackDatabuilder.Clear();
    }

    [RelayCommand]
    public async Task DoSaveFileAsync()
    {
        await SaveToFileAsync("PackingJuanCai");
        await SaveToFileAsync("JC_CM");
        await SaveToFileAsync("JC_Middle");
        await SaveToFileAsync("JC_SSD_RRP_In");
        await SaveToFileAsync("Weight_WriteBack");
        ToastManager.ShowSuccessToast("保存数据成功!");
    }
    
    public async Task doReadDataAsync(int offset,string name)
    {
        switch (name)
        {
            case "PackingJuanCai":
                AppendData(offset, PackingJuanCaibuilder);
                PackingJuanCaiData = PackingJuanCaibuilder.ToString();
                return;
            case "JC_CM":
                AppendData(offset, JCCMDatabuilder);
                JCCMData = JCCMDatabuilder.ToString();
                return;
            case "JC_Middle":
                AppendData(offset, JCMiddleDatabuilder);
                JCMiddleData = JCMiddleDatabuilder.ToString();
                return;
            case "JC_SSD_RRP_In":
                AppendData(offset, JCSSDRRPInDatabuilder);
                JCSSDRRPInData = JCSSDRRPInDatabuilder.ToString();
                return;
            case "Weight_WriteBack":
                AppendData(offset, WeightWriteBackDatabuilder);
                WeightWriteBackData = WeightWriteBackDatabuilder.ToString();
                return;
        }
       
       
    }

    public async Task AppendData(int offset,StringBuilder builder)
    {
        // 添加当前时间（精确到毫秒）
        builder.Append("[ " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " ]   ");
        // 添加方法返回的内容
        // builder.Append(await ReadDataAsync(offset)); // 注意：异步方法需要用await
        builder.Append(await ReadDataHslAsync(offset)); // 注意：异步方法需要用await
        // 添加换行符
        builder.Append(Environment.NewLine);
    }
    
    public async Task<string> ReadDataHslAsync(int offset)
    {
        PlcJuanCaiServiceHsl.Connect();
        PlcJuanCai juanCai = PlcJuanCaiServiceHsl.ReadJuanCaiData(0);
        /*PlcJuanCaiService.Connect();
        PlcJuanCaiInfo juanCai = PlcJuanCaiService.ReadJuanCaiData(0);*/
        string result = JsonConvert.SerializeObject(juanCai, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
        Console.WriteLine(result);
        return result;
    }
    
    public async Task<string> ReadDataAsync(int offset)
    {
        PlcJuanCaiService.Connect();
        PlcJuanCaiInfo juanCai = PlcJuanCaiService.ReadJuanCaiData(offset);
        string result = JsonConvert.SerializeObject(juanCai, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
        Console.WriteLine(result);
        return result;
    }
    
    private async Task SaveToFileAsync(string name)
    {
        try
        {
            // 获取exe所在目录
            string exeDirectory = AppContext.BaseDirectory;
            // 创建子目录
            string subDirectory = Path.Combine(exeDirectory, "ReadData");
        
            // 确保目录存在
            if (!Directory.Exists(subDirectory))
            {
                Directory.CreateDirectory(subDirectory);
            }

            // 创建文件名（使用当前时间戳）
            string fileName = $"{name}_{DateTime.Now:yyyyMMdd_HH_mm_ss}.txt";
            string filePath = Path.Combine(subDirectory, fileName);

            switch (name)
            {
                case "PackingJuanCai":
                        File.WriteAllText(filePath, PackingJuanCaibuilder.ToString());
                    return;
                case "JC_CM":
                        File.WriteAllText(filePath, JCCMDatabuilder.ToString());
                    return;
                case "JC_Middle":
                    File.WriteAllText(filePath, JCCMDatabuilder.ToString());
                    return;
                case "JC_SSD_RRP_In":
                    File.WriteAllText(filePath, JCSSDRRPInDatabuilder.ToString());
                    return;
                case "Weight_WriteBack":
                    File.WriteAllText(filePath, WeightWriteBackDatabuilder.ToString());
                    return;
                
            }
            // 写入文件
           
            
            // 保存最后保存的文件路径
            LastSavedFilePath = filePath;
        }
        catch (Exception ex)
        {
            PackingJuanCaiData += $"\n\n保存文件时出错: {ex.Message}";
        }
    }
    
}

